package com.mantou.scucorse.core.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.mantou.scucorse.core.entity.ScuCourse;
import com.mantou.scucorse.core.entity.Task;
import com.mantou.scucorse.core.service.ScuCourseService;
import com.mantou.scucorse.core.service.TaskService;
import com.mantou.scucorse.core.vo.TaskVO;
import com.mantou.scucorse.utils.ReturnCode;
import com.mantou.scucorse.utils.ReturnContainer;
import com.mantou.scucorse.utils.SystemInfo;

@Controller
@SessionAttributes("userId")
@RequestMapping("/scucorse")
public class TaskRestApiController {

	private final Logger logger = LoggerFactory.getLogger(TaskRestApiController.class);


	@Resource
	private TaskService taskService;

	@Resource
	private ScuCourseService scuCourseService;

	@RequestMapping(value="/core/task/startall/{syskey}",method = RequestMethod.GET)
	public ResponseEntity<ReturnContainer<Integer>>  startAll(@PathVariable String syskey){
		if(!syskey.equals(SystemInfo.syskey)){
			return new ResponseEntity<ReturnContainer<Integer>>(new ReturnContainer<Integer>(ReturnCode.KEYNOTCORRECT.getStatus()
					,ReturnCode.KEYNOTCORRECT.getDescription(),null), HttpStatus.OK);
		}
		taskService.wakeup();
		return new ResponseEntity<ReturnContainer<Integer>>(new ReturnContainer<Integer>(ReturnCode.OK.getStatus(),ReturnCode.OK.getDescription(),null), HttpStatus.OK);
	}

	@RequestMapping(value="/core/task/sleepall/{syskey}",method = RequestMethod.GET)
	public ResponseEntity<ReturnContainer<Integer>>  hiberateAll(@PathVariable String syskey){
		if(!syskey.equals(SystemInfo.syskey)){
			return new ResponseEntity<ReturnContainer<Integer>>(new ReturnContainer<Integer>(ReturnCode.KEYNOTCORRECT.getStatus()
					,ReturnCode.KEYNOTCORRECT.getDescription(),null), HttpStatus.OK);
		}
		taskService.hiberate();
		return new ResponseEntity<ReturnContainer<Integer>>(new ReturnContainer<Integer>(ReturnCode.OK.getStatus(),ReturnCode.OK.getDescription(),null), HttpStatus.OK);
	}

	@RequestMapping(value="/core/tasks",method = RequestMethod.GET)
	public ResponseEntity<ReturnContainer<List<TaskVO>>> getTasks(HttpSession session,Model model){
		Map<String,Object> modelMap = model.asMap();
		if(!modelMap.containsKey("userId")){
			return new ResponseEntity<ReturnContainer<List<TaskVO>>>(new ReturnContainer<List<TaskVO>>(ReturnCode.NOTLOGIN.getStatus(),ReturnCode.NOTLOGIN.getDescription(),null), HttpStatus.OK);
		}
		Integer userId = (Integer) modelMap.get("userId");
		List<Task> tasks = taskService.findByUserID(userId);
		List<TaskVO> taskVOs = new ArrayList<TaskVO>();
		for(Task task:tasks){
			ScuCourse scuCourse = scuCourseService.findByPrimaryKey(task.getCourseid());
			taskVOs.add(map2TaskVO(task,scuCourse));
		}

		return new ResponseEntity<ReturnContainer<List<TaskVO>>>(new ReturnContainer<List<TaskVO>>(ReturnCode.OK.getStatus(),ReturnCode.OK.getDescription(),taskVOs), HttpStatus.OK);
	}

	@RequestMapping(value = "/core/task/restart", method = RequestMethod.PUT)
	public ResponseEntity<ReturnContainer<Integer>> restart(HttpSession session,Model model,@RequestBody List<TaskVO> tasks){
		Map<String,Object> modelMap = model.asMap();
		if(!modelMap.containsKey("userId")){
			return new ResponseEntity<ReturnContainer<Integer>>(new ReturnContainer<Integer>(0,"not login",null), HttpStatus.OK);
		}
		Integer userId = (Integer) modelMap.get("userId");
		List<Integer> restartids = new ArrayList<Integer>();
		for(TaskVO task:tasks){
			if(task.getId() != null && task.getId() > 0){
				restartids.add(task.getId());
			}
		}
		taskService.restart(restartids,userId);
		return new ResponseEntity<ReturnContainer<Integer>>(new ReturnContainer<Integer>(0,"not login",null), HttpStatus.OK);
	}
	@RequestMapping(value = "/core/task/cancel", method = RequestMethod.PUT)
	public ResponseEntity<ReturnContainer<Integer>> cancel(HttpSession session,Model model,@RequestBody List<TaskVO> tasks){
		Map<String,Object> modelMap = model.asMap();
		if(!modelMap.containsKey("userId")){
			return new ResponseEntity<ReturnContainer<Integer>>(new ReturnContainer<Integer>(0,"not login",null), HttpStatus.OK);
		}
		Integer userId = (Integer) modelMap.get("userId");
		List<Integer> cancelIds = new ArrayList<Integer>();
		for(TaskVO task:tasks){
			if(task.getId() != null && task.getId() > 0){
				cancelIds.add(task.getId());
			}
		}
		taskService.cancle(cancelIds,userId);
		return new ResponseEntity<ReturnContainer<Integer>>(new ReturnContainer<Integer>(0,"not login",null), HttpStatus.OK);
	}

	@RequestMapping(value = "/core/task/{id}", method = RequestMethod.GET)
	public ResponseEntity<String> getTaskById(@PathVariable Integer id){
		String responseEnv = new String("");
		return new ResponseEntity<String>(responseEnv, HttpStatus.OK);
	}

	@RequestMapping(value = "/core/task", method = RequestMethod.POST)
	public ResponseEntity<ReturnContainer<TaskVO>> createTask(@RequestBody TaskVO taskVO,HttpSession session,Model model){
		Map<String,Object> modelMap = model.asMap();
		if(!modelMap.containsKey("userId")){
			return new ResponseEntity<ReturnContainer<TaskVO>>(new ReturnContainer<TaskVO>(ReturnCode.NOTLOGIN.getStatus(),ReturnCode.NOTLOGIN.getDescription(),null), HttpStatus.OK);
		}
		int userId = (Integer) modelMap.get("userId");
		Task task = taskService.create(taskVO.getCoursenumber(),taskVO.getSycnumber(),userId);
		ScuCourse queryScuCourse = new ScuCourse();
		queryScuCourse.setCoursenumber(taskVO.getCoursenumber());
		queryScuCourse.setSycnumber(taskVO.getSycnumber());

		TaskVO retVO = map2TaskVO(task,scuCourseService.find(queryScuCourse ));
		return new ResponseEntity<ReturnContainer<TaskVO>>(new ReturnContainer<TaskVO>(ReturnCode.OK.getStatus(),ReturnCode.OK.getDescription(),retVO), HttpStatus.OK);
	}

	@RequestMapping(value = "/core/task/{id}", method = RequestMethod.DELETE)
	public ResponseEntity<Integer> deleteTaskByPrimaryKey(@PathVariable Integer id){
		Integer  result = taskService.deleteByPrimaryKey(id);
		Integer responseEnv = new Integer(result);
		return new ResponseEntity<Integer>(responseEnv, HttpStatus.OK);
	}

	@RequestMapping(value = "/core/task/{id}", method = RequestMethod.PUT)
	public ResponseEntity<Integer> updateTaskByPrimaryKeySelective(@PathVariable Integer id, @RequestBody String taskVO){
		Integer  result = taskService.updateByPrimaryKeySelective(null);
		Integer responseEnv = new Integer(result);
		return new ResponseEntity<Integer>(responseEnv, HttpStatus.OK);
	}

	private static TaskVO map2TaskVO(Task task,ScuCourse scuCourse){
		TaskVO taskvo = new TaskVO();
		taskvo.setBuilding(scuCourse.getBuilding());
		taskvo.setCampus(scuCourse.getCampus());
		taskvo.setChoosecontrol(scuCourse.getChoosecontrol());
		taskvo.setChoosedes(scuCourse.getChoosedes());
		taskvo.setChoosemode(scuCourse.getChoosemode());
		taskvo.setClassroom(scuCourse.getClassroom());
		taskvo.setCoursename(scuCourse.getCoursename());
		taskvo.setCoursenumber(scuCourse.getCoursenumber());
		taskvo.setCredit(scuCourse.getCredit());
		taskvo.setExamination(scuCourse.getExamination());
		taskvo.setId(task.getId());
		taskvo.setLeftnumber(scuCourse.getLeftnumber());
		taskvo.setOffset(scuCourse.getOffset());
		taskvo.setProperty(scuCourse.getProperty());
		taskvo.setSchoolYear(scuCourse.getSchoolYear());
		taskvo.setStatus(task.getStatus());
		taskvo.setSycnumber(scuCourse.getSycnumber());
		taskvo.setTeachername(scuCourse.getTeachername());
		taskvo.setWeek(scuCourse.getWeek());
		taskvo.setWeeks(scuCourse.getWeeks());
		return taskvo;
	}
}
